<?php

/**
 * Impress - Open source digital signage
 *
 * @link http://digitalsignage.tk
 * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
 *
 * @category Impress
 * @package Impress
 */

/**
 * This class provides access to data layer.
 *
 * @package Impress
 * @subpackage Models
 */

class ADS_WPModel extends ADS_DefaultModel {
    
    private $translateContent = array(
        'image' => 'attachment',
        'video' => 'attachment',
        'post'  => 'post'
    );


    public function getPosts($content) {
        if(!is_string($content)){
            throw new InvalidArgumentException(sprintf('Wrong parameters for method %s.',__METHOD__));
        }
        return dibi::fetchAll('
          SELECT
            t1.post_title AS name,
            t1.ID AS itemId
          FROM
            [:wp:posts] AS t1
          WHERE
            post_type = %s
          AND 
            %and
          ', $this->translateContent[$content], array(
            array('t1.post_status != %s', 'auto-draft'),
            array('t1.post_status != %s', 'private')
          ),'
          %if', $this->translateContent[$content] == 'attachment','
          AND
            post_mime_type LIKE %like~', sprintf('%s/', $content)
        );
    }
    
    public function getPostsWithTag($content, $tagId) {
        if(!is_string($content) || !is_int($tagId)){
            throw new InvalidArgumentException(sprintf('Wrong parameters for method %s.',__METHOD__));
        }
        return dibi::fetchAll('
            SELECT
                t4.*
            FROM
                [:wp:term_taxonomy] AS t1
            INNER JOIN
                [:wp:term_relationships] AS t2 USING (term_taxonomy_id)
            INNER JOIN
                [:wp:posts] AS t3 ON t3.ID = t2.object_id
            INNER JOIN
                [:wp:posts] AS t4 ON t3.ID = t4.post_parent
            WHERE
                t4.post_type = %s', $this->translateContent[$content],'
            %if', $this->translateContent[$content] == 'attachment','
            AND 
                t4.post_mime_type LIKE %like~', sprintf('%s/', $content), '
            AND
                t1.term_id = %i
            AND
                %and
        ', $tagId, array(
            array('t4.post_status != %s', 'auto-draft'),
            array('t4.post_status != %s', 'private')
        ));
    }  
    
    public function getTags() {
        return dibi::fetchAll('
          SELECT
            t1.name,
            t1.term_id AS tagId
          FROM
            [:wp:terms] AS t1
          INNER JOIN
            [:wp:term_taxonomy] AS t2 USING (term_id)
          WHERE
            t2.taxonomy = %s
        ', 'post_tag');
    }    
}
